package cn.lingyangwl.agile.pay.pay.controller.qr;

import cn.lingyangwl.agile.pay.common.service.PaySysConfigService;
import cn.lingyangwl.agile.pay.common.utils.PayUtils;
import cn.lingyangwl.agile.pay.pay.channel.AbstractChannelUserService;
import cn.lingyangwl.agile.pay.pay.channel.IChannelUserService;
import cn.lingyangwl.agile.pay.pay.model.bo.MchAppConfigContext;
import cn.lingyangwl.agile.pay.pay.model.rqrs.ChannelUserIdRQ;
import cn.lingyangwl.framework.tool.core.StringUtils;
import cn.lingyangwl.framework.tool.core.exception.Assert;
import cn.lingyangwl.framework.tool.core.exception.BizException;
import cn.lingyangwl.agile.pay.constant.IfCodeEnum;
import cn.lingyangwl.agile.pay.pay.service.ConfigContextQueryService;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 商户获取渠道用户ID接口
 *
 * @author shenguangyang
 */
@RestController
@RequestMapping("/channelUserId")
public class ChannelUserIdController {
    @Resource
    private ConfigContextQueryService configContextQueryService;
    @Resource
    private PaySysConfigService sysConfigService;
    @Resource
    protected HttpServletRequest request;
    @Resource
    protected HttpServletResponse response;

    /**
     * 重定向到微信地址
     */
    @GetMapping("/jump")
    public void jump(ChannelUserIdRQ rq) throws Exception {
        // 获取请求数据
//        ChannelUserIdRQ rq = getRQByWithMchSign(ChannelUserIdRQ.class);

        String ifCode = "AUTO".equalsIgnoreCase(rq.getIfCode()) ? getIfCodeByUA() : rq.getIfCode();

        // 获取接口
        IChannelUserService channelUserService = AbstractChannelUserService.getService(ifCode);

        if(channelUserService == null){
            throw new BizException("不支持的客户端");
        }

        if(!StringUtils.isAvailableUrl(rq.getRedirectUrl())){
            throw new BizException("跳转地址有误！");
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("mchNo", rq.getMchNo());
        jsonObject.put("appId", rq.getAppId());
        jsonObject.put("extParam", rq.getExtParam());
        jsonObject.put("ifCode", ifCode);
        jsonObject.put("redirectUrl", rq.getRedirectUrl());

        // 回调地址
        String callbackUrl = sysConfigService.getDBApplicationConfig().genMchChannelUserIdApiOauth2RedirectUrlEncode(jsonObject);

        // 获取商户配置信息
        MchAppConfigContext mchAppConfigContext = configContextQueryService.queryMchInfoAndAppInfo(rq.getMchNo(), rq.getAppId());
        Assert.notNull(mchAppConfigContext, new BizException("商户号和商户应用不匹配"));
        String redirectUrl = channelUserService.buildUserRedirectUrl(callbackUrl, mchAppConfigContext);
        response.sendRedirect(redirectUrl);
    }


    /**
     * 回调地址
     */
    @GetMapping("/oauth2Callback/{aesData}")
    public void oauth2Callback(@PathVariable("aesData") String aesData, @RequestParam JSONObject jsonObject) throws Exception {

        JSONObject callbackData = JSON.parseObject(PayUtils.aesDecode(aesData));

        String mchNo = callbackData.getString("mchNo");
        String appId = callbackData.getString("appId");
        String ifCode = callbackData.getString("ifCode");
        String extParam = callbackData.getString("extParam");
        String redirectUrl = callbackData.getString("redirectUrl");

        // 获取接口
        IChannelUserService channelUserService = AbstractChannelUserService.getService(ifCode);

        if(channelUserService == null){
            throw new BizException("不支持的客户端");
        }

        // 获取商户配置信息
        MchAppConfigContext mchAppConfigContext = configContextQueryService.queryMchInfoAndAppInfo(mchNo, appId);

        // 获取渠道用户ID
        String channelUserId = channelUserService.getChannelUserId(jsonObject, mchAppConfigContext);

        // 同步跳转
        JSONObject appendParams = new JSONObject();
        appendParams.put("appId", appId);
        appendParams.put("channelUserId", channelUserId);
        appendParams.put("extParam", extParam);
        response.sendRedirect(StringUtils.appendUrlQuery(redirectUrl, appendParams));
    }


    /** 根据UA获取支付接口 */
    private String getIfCodeByUA() {
        String ua = request.getHeader("User-Agent");

        // 无法识别扫码客户端
        if (StringUtils.isBlank(ua)) {
            return null;
        }

        if(ua.contains("Alipay")) {
            return IfCodeEnum.ALIPAY.getCode();  //支付宝服务窗支付
        }else if(ua.contains("MicroMessenger")) {
            return IfCodeEnum.WXPAY.getCode();
        }
        return null;
    }
}
